package cn.zd.demo1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

import cn.zd.demo1.util.ViewCheckUtil;

public class SharedPreferencesActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_read;
    private TextView tv_save;
    private EditText et_string;
    private EditText et_int;
    private SharedPreferences demodata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toast.makeText(this,this.getClass().getName(),Toast.LENGTH_LONG).show();
        setContentView(R.layout.activity_sharedpreferences);
        Button btn_save = findViewById(R.id.btn_save);
        Button btn_read = findViewById(R.id.btn_read);
        tv_save = findViewById(R.id.tv_save);
        tv_read = findViewById(R.id.tv_read);
        et_string = findViewById(R.id.et_string);
        et_int = findViewById(R.id.et_int);
        btn_read.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        //1. 得到sp对象，Context.MODE_PRIVATE表示文件模式，是否是私有的，即其他应用是否可以访问
        demodata = getSharedPreferences("demodata", Context.MODE_PRIVATE);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_save) {
            SharedPreferences.Editor edit = demodata.edit();
            if(!ViewCheckUtil.checkEditText(et_string) || !ViewCheckUtil.checkEditText(et_int)) {
                Toast.makeText(this,"写点东西~",Toast.LENGTH_SHORT).show();
                return;
            }
            edit.putString("data_string", et_string.getText().toString());
            edit.putInt("data_int", Integer.parseInt(et_int.getText().toString()));
            float f = new Random().nextFloat();
            edit.putFloat("data_float", f);
            edit.commit();
            Toast.makeText(this,"保存成功,生成随机浮点数："+f,Toast.LENGTH_SHORT).show();
            tv_save.setText("存储位置："+Environment.getDataDirectory() + "/data/"+getPackageName()+"/shared_prefs/demodata.xml");
        } else if (v.getId() == R.id.btn_read) {
            tv_read.setText(String.format("字符串数据：[%s],整型：[%d]，浮点型：[%f]",demodata.getString("data_string",null),demodata.getInt("data_int",0),demodata.getFloat("data_float",0.0f)));
            Toast.makeText(this,"读取成功",Toast.LENGTH_SHORT).show();
        }
    }

}